<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Validate;
use app\index\model\Member as MemberModel;
class Login extends Controller
{
    public function _initialize()
    {
        $show['show'] = 1;
        $LinksList = Db::name('links')->where($show)->order('id desc')->select();
        $this->assign('LinksList', $LinksList);
    }

    /**
     * 第一版：pc和移动端登录
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $MemberMd = new MemberModel();
		if (request()->isPost()) {
            $this->check(input('code'));
            $data = input('post.');
			$status['status'] = 1;
            $user = $MemberMd->where($status)->where('usermail', $data['usermail'])->find();
            if ($user) {
                if ($user['password'] == substr(md5($data['password']), 8, 16)) {
					session('userhead', $user['userhead']);
                    session('username', $user['username']);
                    session('userid', $user['userid']);
                    session('grades', $user['grades']);
					session('point', $user['point']);
					$MemberMd->where('userid',session('userid'))->setInc('point',config('point.LOGIN_POINT'));
                    return json(array('code' => 200, 'msg' => '登录成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '密码错误'));
                }
            } else {
                return json(array('code' => 0, 'msg' => '账号错误'));
            }
        }
        return view();
    }

    /**
     * 第一版：pc和移动端注册
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function reg()
    {
        $MemberMd = new MemberModel();
        if (request()->isPost()) {
            $this->check(input('code'));
            $data = input('post.');
			$webreg = 1;
            $password = input('password');
            $passwords = input('passwords');
            $mail = $MemberMd->where('usermail', $data['usermail'])->find();
            if (!$mail) {
                $user = $MemberMd->where('username', $data['username'])->find();
                if (!$user) {
                    if ($password != $passwords) {
                        return json(array('code' => 0, 'msg' => '密码错误'));
                    }
					if ($webreg != config('web.WEB_REG')) {
                        return json(array('code' => 0, 'msg' => '已关闭会员注册'));
                    }
                    $data['regtime'] = time();
                    $data['grades'] = 0;
                    /*$data['status'] = config('web.WEB_REG');*/
                    $data['status'] = 0;
                    $data['point'] = config('point.REG_POINT');
                    $data['userhead'] = '/public/img/user-default.png';
                    $data['userip'] = $_SERVER['REMOTE_ADDR'];
                    $data['password'] = substr(md5($password), 8, 16);
                    if ($MemberMd->add($data)) {
                        return json(array('code' => 200, 'msg' => '注册成功'));
                    } else {
                        return json(array('code' => 0, 'msg' => '注册失败'));
                    }
                } else {
                    return json(array('code' => 0, 'msg' => '该昵称已存在'));
                }
            } else {
                return json(array('code' => 0, 'msg' => '该邮箱已存在'));
            }
        }
        return view();
    }

    /**
     * 通用验证码验证
     * @param string $code
     * @return bool
     */
    public function check($code = '')
    {
        if (!captcha_check($code)) {
            $this->error('验证码错误');
        } else {
            return true;
        }
    }


    /**
     * 第二版：移动端登录
     * @return array|mixed|\think\response\Json|\think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function member_login()
    {
        $MemberMd = new MemberModel();
        if(request()->isPost()){
            $mobile = input("post.mobile");
            $password = input("post.password");
            $token = input("post.token");

            $data = [
                'mobile'  => $mobile,
                'password'  => $password,
                '__token__' => $token,
            ];
            $rule = [
                'mobile'    => 'require|max:11/^1[3-8]{1}[0-9]{9}$/',
                'password'  => 'require|length:8,16',
                '__token__' => 'token',
            ];
            $msg = [
                'mobile.require'   => '手机号不能为空！',
                'mobile.max'       => '请输入正确的手机号！',
                'password.require' => '密码不能为空！',
                'password.length'  => '请输入8-16位密码！',
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }
            $user = $MemberMd->where('mobile', $mobile)->find();
            if($user){
                if($user['status'] == 1){
                    if ($user['password'] == substr(md5($password), 8, 16)) {
                        session('userhead', $user['userhead']);
                        session('username', $user['username']);
                        session('userid', $user['userid']);
                        session('grades', $user['grades']);
                        session('point', $user['point']);
                        session('mobile', $user['mobile']);
                        $MemberMd->where('userid',session('userid'))->setInc('point',config('point.LOGIN_POINT'));
                        return json(array('code' => 200, 'msg' => '登录成功'));
                    } else {
                        return json(array('code' => 0, 'msg' => '帐号或密码错误'));
                    }
                }else{
                    return json(array('code' => 0, 'msg' => '帐号异常、请联系管理员'));
                }
            }else{
                return json(['code'=>0,'msg'=>'此用户不存在']);
            }
        }
        return view();
    }

    /**
     * 第二版：移动端注册
     * @return array|mixed|\think\response\View
     */
    public function member_register()
    {
        $MemberMd = new MemberModel();
        if(request()->isPost()){

            // 验证是否开启注册功能
            $webreg = 1;
            if ($webreg != config('web.WEB_REG')) {
                return json(array('code' => 0, 'msg' => '已关闭会员注册、请联系管理员'));
            }

            $mobile = input("post.mobile");
            $code = input("post.code");
            $password = input("post.password");
            $password_confirm = input("post.password_confirm");
            $token = input("post.token");
            $invitation_code = input("post.invitation_code");

            $data = [
                'mobile'  => $mobile,
                'password'  => $password,
                'password_confirm'  => $password_confirm,
//                'code' => $code,
                '__token__' => $token,
            ];
            $rule = [
                'mobile'    => 'require|max:11/^1[3-8]{1}[0-9]{9}$/',
                'password'  => 'require|confirm:password_confirm|length:8,16',
//                'code'  => 'require|captcha',
                '__token__' => 'token',
            ];
            $msg = [
                'mobile.require'   => '手机号不能为空！',
                'mobile.max'       => '请输入正确的手机号！',
                'username.max'     => '名称最多不能超过25个字符！',
                'password.require' => '密码不能为空！',
                'password.confirm' => '密码输入不一致！',
                'password.length'  => '请输入8-16位密码！',
//                'code.require'  => '验证码不能为空！',
//                'code.captcha'  => '验证码错误！',
                '__token__'  => '非法操作！',
            ];
            $validate   = Validate::make($rule,$msg);
            if (!$validate->check($data)) {
                return json(['code'=>0,'msg'=>$validate->getError()]);
            }

            //用邀请码查找推荐人id
            $parent_id = substr($invitation_code,strrpos($invitation_code,'T')+1);
            $parent_user_id = $MemberMd->where('userid',$parent_id)->value('userid');

            $userid = $MemberMd->where('mobile',$mobile)->value('userid');
            if(!$userid){
                $item['username'] = $mobile;
                $item['mobile'] = $mobile;
                $item['regtime'] = time();
                $item['grades'] = 0;
                $item['status'] = 1;
                $item['point'] = config('point.REG_POINT');
                $item['userhead'] = '/public/img/user-default.png';
                $item['userip'] = $_SERVER['REMOTE_ADDR'];
                $item['password'] = substr(md5($password), 8, 16);
                $item['parent_id'] = empty($parent_user_id) ? 1 : $parent_user_id;
                $user_id = $MemberMd::add_user($item);
                unset($item);
                if ($user_id) {
                    $item['invitation_code'] = $this->randomkeys(5).'T'.$user_id;//生成自己的邀请码
                    $MemberMd::edit_user($user_id,$item);
                    return json(array('code' => 200, 'msg' => '注册成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '注册失败'));
                }
            }else{
                return json(['code'=>0,'msg'=>'此手机号用户已注册']);
            }
        }
        $invitation_code = $MemberMd->where('userid',1)->value('invitation_code');//没有默认总管理员邀请码
        $invitation_code = empty(input("get.invitation_code")) ? $invitation_code : input("get.invitation_code");
        $this->assign('invitation_code',$invitation_code);
        return view();
    }

    /**
     * 通用退出
     * @return null|\think\response\Json
     */
    public function logout()
    {
        session("userid", NULL);
        session("grades", NULL);
        session("username", NULL);
		session("usermail", NULL);
        session("kouling", NULL);
        session("mobile", NULL);
        return json(array('code' => 200, 'msg' => '退出成功'));
        return NULL;
    }

    public function randomkeys($length)
    {
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $key = '';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,35)};//生成随机数
        }
        return $key;
    }


}